package com.iamteer.day10;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Context
 */
@WebServlet("/Context")
public class Context extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Context() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取 context
		ServletContext context = this.getServletContext();
		String contextPath = context.getContextPath();
		System.out.println(contextPath);
		//利用 context 获取当前应用路径，进行资源重定向
		response.sendRedirect(contextPath + "/index.html");
		
		//获取参数
		System.out.println("参数：" + context.getInitParameter("AAA"));	//获取某个参数
		//获取所有参数
		Enumeration<String> enums = context.getInitParameterNames();
		while (enums.hasMoreElements()) {
			String name = (String) enums.nextElement();
			String value = context.getInitParameter(name);
			System.out.println(name + "=" + value);
		}
		
		//通过域对象共享数据
		context.setAttribute("student", new Student("chuck", 20));
		System.out.println("保存成功！");
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

class Student{
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [age=" + age + ", name=" + name + "]";
	}
	
}
